const db = require('../db/index')
exports.getArticle = (req, res) => {
        const pageNum = parseInt(req.query.pageNum);
        const page = parseInt(req.query.page);
        // console.log(pageNum, page);
        //获取总数
        const sql1 = 'select * from article '
        var pageTotal = ''
        db.query(sql1, (err, result) => {
                // return res.send(result.length)
                // console.log(result.length);
                pageTotal = result.length
            })
            //查询数据
            // res.send('获取文章')
        const sql2 = `SELECT article.id,title,likeCount,views,createtime,username FROM article left join user on(article.user_id=user.id)order by id desc LIMIT ?,?`
        db.query(sql2, [pageNum * page, pageNum], (err, result) => {
            if (err) return res.send({ status: 201, message: err.message });
            res.send({ status: 200, total: pageTotal, message: '获取文章数据成功', data: result, })
        })
    }
    //删除文章
exports.delArticle = (req, res) => {
    // console.log(req);
    const sql = 'delete from article where id=?'
    db.query(sql, req.query.id, (err, result) => {
        if (err) return res.send({ status: 201, message: '删除失败' })
        res.send({
            status: 200,
            message: '删除成功'
        })
    })
}
exports.addArticle = (req, res) => {
    const title = req.body.title
    const content = req.body.content
    const author = req.body.user_id
    const datatime = new Date()
    const sql = 'insert into article (title,content,likeCount,views,createtime,user_id) values (?,?,0,0,?,?)'
    db.query(sql, [title, content, datatime, author], (err, result) => {
        if (err) return res.send({ status: 201, message: err.message })
        res.send({
            status: 200,
            message: '添加成功'
        })
    })
}